package com.famdoc.Exception;

import com.famdoc.Pojo.dto.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@RestControllerAdvice
public class ExceptionControllerAdvice {
    /**
     * 处理特定异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach((fieldError -> {
                String field = fieldError.getField();
                String message = fieldError.getDefaultMessage();
                map.put(field, message);
            }));
        }
        return Result.error(201,"数据检验不通过", map);
    }

    /**
     * 处理其他异常
     *
     * @return
     */
//    @ExceptionHandler(value = Exception.class)
//    public Result handleException() {
//        return Result.error(500,"服务器内部异常");
//    }

}
